import fs from 'fs';
import path from 'path';

export function isFileType(file: string, extensions: string[] = []) {
    const ext = path.extname(file).toLowerCase();
    return extensions.includes(ext);
}

export const deleteFile = (
    directory: string,
    options?: {
        recurs?: boolean,
        extensions?: string[]
    }
) => {
    const {recurs = false, extensions = []} = options || {};
    const files = fs.readdirSync(directory);

    files.forEach(file => {
        const filePath = path.join(directory, file);
        const stat = fs.statSync(filePath);

        if (stat.isFile() && isFileType(file, extensions)) {
            fs.unlinkSync(filePath);
            console.log('delete file: ' + filePath);
        } else if (recurs && stat.isDirectory()) {
            deleteFile(filePath, options);
        }
    });
};
